import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_widgets_pc/config/kq_global.dart';
import 'package:flutter_widgets_pc/widgets/dialog/kq_confirm_dialog.dart';
import 'package:flutter_widgets_pc/widgets/dialog/kq_msg_dialog.dart';

import '../resources/l10n/kq_intl.dart';
import '../widgets/bottomSheet/kq_botton_sheet_manger.dart';
import '../widgets/bottomSheet/sheets/kq_date_picker_bottom_sheet.dart';
import '../widgets/dialog/kq_custom_dialog.dart';
import '../widgets/dialog/kq_date_picker_dialog.dart';
import '../widgets/dialog/kq_input_dialog.dart';
import '../widgets/dialog/kq_list_dialog.dart';
import '../widgets/dialog/kq_opt_dialog.dart';
import '../widgets/dialog/kq_reason_dialog.dart';

/// 通用对话框，简化调用过程
class KqDialog {
  ///消息对话框
  ///
  /// 顶部标题
  /// 中间内容
  /// 底部1个按钮-我知道了
  static showMsgDialog(
      {String? title,
      required String msg,
      TextAlign? msgTextAlign,
      String? btnText,
        double? maxHeight,
      bool barrierDismissible = true,
      GestureTapCallback? onBtnTap,
      Function()? onDismiss}) {
    showDialog(
        context: KqGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        builder: (context) {
          return KqMsgDialog(
            titleString: title,
            msg: msg,
            btnText: btnText ?? KqIntl.currentResource.known,
            maxHeight: maxHeight,
            msgTextAlign: msgTextAlign,
            onBtnTap: () {
              Navigator.pop(context);
              onBtnTap?.call();
            },
          );
        }).then((value) => onDismiss?.call());
  }

  /// 确认对话框，
  ///
  /// 顶部标题
  /// 中间内容
  /// 底部两个按钮-取消和确定
  static showConfirmDialog(
      {String? title,
      required String msg,
      TextAlign? msgTextAlign,
      String? leftBtnText,
      String? rightBtnText,
      double? dialogWidth,
      Color? leftBtnColor,
      Color? rightBtnColor,
      bool barrierDismissible = true,
      GestureTapCallback? onConfirm,
      GestureTapCallback? onCancel,
      Function()? onDismiss}) {
    showDialog(
        context: KqGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        builder: (context) {
          return KqConfirmDialog(
            titleString: title,
            msg: msg,
            msgTextAlign: msgTextAlign,
            leftBtnText: leftBtnText,
            rightBtnText: rightBtnText,
            leftBtnColor: leftBtnColor,
            rightBtnColor: rightBtnColor,
            dialogWidth: dialogWidth,
            onLeftBtnTap: () {
              Navigator.pop(context);
              onCancel?.call();
            },
            onRightBtnTap: () {
              Navigator.pop(context);
              onConfirm?.call();
            },
          );
        }).then((value) => onDismiss?.call());
  }

  /// 输入对话框
  ///
  /// defValue : 默认值
  /// maxLines : 最大行数，默认1
  /// multiline : 是否支持多行，默认false
  /// altEnterNewLine : 是否使用Alt+Enter换行
  /// allowEmpty : 内容为空是否允许确定，默认true
  /// inputTextAlign : 输入框内容对齐方式
  /// inputFormatters : 输入框内容格式限制
  /// inputType : 键盘类型
  /// autoDismissWhenTapMiddle : 是否点击中间按钮自动关闭对话框，默认true
  /// onEmptyCallback : allowEmpty = false 时，输入为空提交回调
  /// onConfirm : 确认点击回调
  static showInputDialog(String title,
      {String? placeHolder,
      String? defValue,
      bool multiline = false,
      bool altEnterNewLine = false,
      int? maxLines,
      bool password = false,
      bool allowEmpty = true,
      bool barrierDismissible = true,
      TextAlign? inputTextAlign,
      TextInputType? inputType,
      String? leftBtnText,
      String? rightBtnText,
      String? middleBtnText,
      Color? middleBtnTextColor,
      int? maxCharCount,
      double? dialogWidth,
      double? maxHeight,
      List<Widget>? customWidgetsAboveInput,
      List<Widget>? customWidgetsBelowInput,
      List<TextInputFormatter>? inputFormatters,
      bool autoDismissWhenTapRight = true,
      bool autoDismissWhenTapMiddle = true,
      bool autoSubmitWhenReturn = true,
      Function()? onEmptyCallback, //allowEmpty = false 时，输入为空提交回调
      Function(String value)? onLeftBtnClick,
      Function(String value)? onMiddleBtnClick,
      required Function(String value) onConfirm,
      Function()? onDismiss}) {
    showDialog(
        context: KqGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        builder: (context) {
          return KqInputDialog(
            defValue: defValue,
            titleString: title,
            dialogWidth: dialogWidth,
            maxHeight: maxHeight,
            enableClearButton: false,
            multiline: multiline,
            altEnterNewLine: altEnterNewLine,
            placeHolder: placeHolder,
            inputType: inputType ??
                (multiline ? TextInputType.multiline : TextInputType.text),
            password: password,
            maxCharCount: maxCharCount,
            inputTextAlign: inputTextAlign,
            inputFormatters: inputFormatters,
            maxLines: multiline ? maxLines : (maxLines ?? 1),
            editController: TextEditingController(),
            autoSubmitWhenReturn: autoSubmitWhenReturn,
            customWidgetsAboveInput: customWidgetsAboveInput,
            customWidgetsBelowInput: customWidgetsBelowInput,
            leftBtnText: leftBtnText,
            rightBtnText: rightBtnText,
            middleBtnText: middleBtnText,
            middleBtnTextColor: middleBtnTextColor,
            onLeftBtnTap: (value) {
              if (onLeftBtnClick == null) {
                Navigator.pop(context);
              } else {
                onLeftBtnClick.call(value);
              }
            },
            onMiddleBtnTap: (value) {
              if (autoDismissWhenTapMiddle) {
                Navigator.pop(context);
              }
              onMiddleBtnClick?.call(value);
            },
            onRightBtnTap: (value) {
              if (allowEmpty || value.isNotEmpty) {
                if (autoDismissWhenTapRight) {
                  Navigator.pop(context);
                }
                onConfirm(value);
              } else {
                if (onEmptyCallback != null) {
                  onEmptyCallback();
                }
              }
            },
          );
        }).then((value) => onDismiss?.call());
  }

  /// 列表对话框
  static showListDialog<T>(List<T> items,
      {bool barrierDismissible = true,
      double? width,
      String Function(int index, T item)? nameConvert,
      Function(int index, T item)? callback,
      Function()? onDismiss}) {
    if (items.isEmpty) {
      return;
    }
    showDialog(
        context: KqGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        builder: (context) {
          return KqListDialog(
              items: items,
              width: width,
              nameConvert: nameConvert,
              callback: (index, item) {
                Navigator.pop(context);
                if (callback != null) {
                  callback(index, item);
                }
              });
        }).then((value) => onDismiss?.call());
  }

  /// 操作对话框，
  ///
  /// 顶部标题和关闭按钮
  /// 中间自定义内容
  /// 底部1个按钮-确定
  static showOptDialog(
      {String? title,
      required Widget child,
      String? btnText,
      double? width,
      double? height,
      bool barrierDismissible = true,
      GestureTapCallback? onBtnTap,
      Function()? onDismiss}) {
    showDialog(
        context: KqGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: Colors.black.withOpacity(0.2),
        builder: (context) {
          return KqPadOptDialog(
            titleString: title,
            btnText: btnText,
            width: width,
            height: height,
            child: child,
            onBtnTap: () {
              Navigator.pop(context);
              onBtnTap?.call();
            },
          );
        }).then((value) => onDismiss?.call());
  }

  // 自定义弹窗
  static showCustomDialog({
    String? title,
    required Widget Function() customWidgetBuilder,
    Widget? Function(BuildContext context, Function()? onCancel)?
        customBtnWidget,
    String? leftBtnText,
    String? rightBtnText,
    Color? leftBtnColor,
    Color? rightBtnColor,
    double? width,
    double? elevation,
    Color? bgColor,
    Color? barrierColor,
    bool barrierDismissible = true,
    Function()? onLeftTap,
    Function()? onRightTap,
    bool isShowLeft = true,
    bool isShowRight = true,
    bool closeWhenTapLeft = true,
    bool closeWhenTapRight = true,
    double? customTopPadding,
    double? customBottomPadding,
    Function()? onDismiss,
  }) {
    showDialog(
        context: KqGlobal.globalContext,
        barrierDismissible: barrierDismissible,
        barrierColor: barrierColor,
        builder: (context) {
          return KqCustomDialog(
            titleString: title,
            customWidgetBuilder: customWidgetBuilder,
            width: width,
            elevation: elevation,
            customBtnWidget: customBtnWidget?.call(context, onLeftTap),
            leftBtnText: leftBtnText,
            //左侧灰色
            rightBtnText: rightBtnText,
            //右侧蓝色
            leftBtnColor: leftBtnColor,
            rightBtnColor: rightBtnColor,
            bgColor: bgColor,
            isShowLeft: isShowLeft,
            isShowRight: isShowRight,
            customTopPadding: customTopPadding,
            customBottomPadding: customBottomPadding,
            onLeftBtnTap: () {
              if (closeWhenTapLeft) {
                Navigator.pop(context);
              }
              onLeftTap?.call();
            },
            onRightBtnTap: () {
              if (closeWhenTapRight) {
                Navigator.pop(context);
              }
              onRightTap?.call();
            },
          );
        }).then((value) => onDismiss?.call());
  }

  ///类似原因的对话框
  static showReasonDialog(
      {required String title,
      required String Function(int index)? renderTitleCallback,
      required int? totalCount,
      double? dialogWidth,
      int maxRowForScroll = 6,
      Function(int index)? callBack}) {
    return showDialog(
        context: KqGlobal.globalContext,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return KqReasonDialog(
            title: title,
            renderTitleCallback: renderTitleCallback,
            totalCount: totalCount,
            dialogWidth: dialogWidth,
            maxRowForScroll: maxRowForScroll,
            callBack: ((index) {
              Navigator.pop(context);
              if (callBack != null) {
                callBack(index);
              }
            }),
          );
        }).then((value) {});
  }

  /// 日期选择
  static showDatePicker(
    String title, {
    bool barrierDismissible = true,
    DateTime? minDateTime,
    DateTime? maxDateTime,
    DateTime? initialDateTime,
    String? leftBtnText,
    String? rightBtnText,
    Function(DateTime dateTime, List<int> selectedIndex)? onConfirm,
    Function(DateTime dateTime, List<int> selectedIndex)? onChange,
    Function()? onClose,
    Function()? onCancel,
  }) {
    return showDialog(
      context: KqGlobal.globalContext,
      barrierDismissible: barrierDismissible,
      builder: (context) => KqDatePickerDialog(
          initialDateTime: initialDateTime ?? DateTime.now(),
          pickerMode: KqDateTimePickerMode.datetime,
          minDateTime: minDateTime,
          maxDateTime: maxDateTime,
          leftBtnText: leftBtnText,
          rightBtnText: rightBtnText,
          pickerTitleConfig: KqPickerTitleConfig(titleContent: title),
          dateFormat: 'yyyy年,MM月,dd日',
          onConfirm: onConfirm,
          onClose: onClose,
          onCancel: onCancel,
          onChange: onChange),
    );
  }

  /// 时间选择对话框
  static showTimePicker(
    String title, {
    bool barrierDismissible = true,
    DateTime? minDateTime,
    DateTime? maxDateTime,
    DateTime? initialDateTime,
    String? leftBtnText,
    String? rightBtnText,
    Function(DateTime dateTime, List<int> selectedIndex)? onConfirm,
    Function(DateTime dateTime, List<int> selectedIndex)? onChange,
    Function()? onClose,
    Function()? onCancel,
  }) {
    return showDialog(
      context: KqGlobal.globalContext,
      barrierDismissible: barrierDismissible,
      builder: (context) => KqDatePickerDialog(
          initialDateTime: initialDateTime ?? DateTime.now(),
          pickerMode: KqDateTimePickerMode.datetime,
          minDateTime: minDateTime,
          maxDateTime: maxDateTime,
          leftBtnText: leftBtnText,
          rightBtnText: rightBtnText,
          pickerTitleConfig: KqPickerTitleConfig(titleContent: title),
          dateFormat: 'HH时:mm分:ss秒',
          onConfirm: onConfirm,
          onClose: onClose,
          onCancel: onCancel,
          onChange: onChange),
    );
  }

  /// 日期时间选择对话框
  static showDateTimePicker(
    String title, {
    bool barrierDismissible = true,
    bool withSecond = true,
    bool withMinute = true,
    DateTime? minDateTime,
    DateTime? maxDateTime,
    DateTime? initialDateTime,
    String? leftBtnText,
    String? rightBtnText,
    Function(DateTime dateTime, List<int> selectedIndex)? onConfirm,
    Function(DateTime dateTime, List<int> selectedIndex)? onChange,
    Function()? onClose,
    Function()? onCancel,
  }) {
    return showDialog(
      context: KqGlobal.globalContext,
      barrierDismissible: barrierDismissible,
      builder: (context) => KqDatePickerDialog(
          initialDateTime: initialDateTime ?? DateTime.now(),
          pickerMode: KqDateTimePickerMode.datetime,
          minDateTime: minDateTime,
          maxDateTime: maxDateTime,
          leftBtnText: leftBtnText,
          rightBtnText: rightBtnText,
          pickerTitleConfig: KqPickerTitleConfig(titleContent: title),
          dateFormat:
              'yyyy年,MM月,dd日,HH时${withMinute ? ':mm分' : ''}${withSecond ? ':ss秒' : ''}',
          onConfirm: onConfirm,
          onClose: onClose,
          onCancel: onCancel,
          onChange: onChange),
    );
  }

  /// 显示loading
  static void showLoading({String? msg, bool showMask = false}) {
    EasyLoading.show(
        status: msg ?? KqIntl.currentResource.loading,
        maskType:
            showMask ? EasyLoadingMaskType.black : EasyLoadingMaskType.clear);
  }

  /// 关闭loading
  static void closeLoading({bool animation = false}) {
    EasyLoading.dismiss(animation: animation);
  }
}
